from flask import Flask, jsonify, request
from flask_cors import CORS
import pymysql
import json

app = Flask(__name__)
CORS(app)  # 允许跨域请求

# 数据库连接配置
DB_CONFIG = {
    'host': 'localhost',
    'user': 'root',
    'password': '123456',  # 请修改为实际密码
    'db': 'fruit',
    'charset': 'utf8mb4',
    'cursorclass': pymysql.cursors.DictCursor
}


# 连接数据库
def get_db_connection():
    try:
        return pymysql.connect(**DB_CONFIG)
    except pymysql.Error as e:
        print(f"数据库连接失败: {e}")
        return None


# 根路径测试
@app.route('/', methods=['GET'])
def index():
    return jsonify({"message": "水果蔬菜信息API服务正在运行"})


# 获取所有水果和蔬菜数据
@app.route('/api/items', methods=['GET'])
def get_all_items():
    try:
        conn = get_db_connection()
        if not conn:
            return jsonify({"error": "数据库连接失败"}), 500

        with conn.cursor() as cursor:
            # 查询所有数据
            cursor.execute("SELECT * FROM fruit_vegetable")
            items = cursor.fetchall()

        # 处理数据以适应前端
        for item in items:
            # 将id转为整数
            item['id'] = int(item['id'])
            # 处理可能的NULL值
            item['another_name'] = item['another_name'] if item['another_name'] else ""

        print(f"成功获取{len(items)}条数据")
        return jsonify(items)

    except pymysql.Error as e:
        print(f"获取数据失败: {e}")
        return jsonify({"error": str(e)}), 500


# 根据ID获取单个项目
@app.route('/api/items/<int:item_id>', methods=['GET'])
def get_item_by_id(item_id):
    try:
        conn = get_db_connection()
        if not conn:
            return jsonify({"error": "数据库连接失败"}), 500

        with conn.cursor() as cursor:
            cursor.execute("SELECT * FROM fruit_vegetable WHERE id = %s", (item_id,))
            item = cursor.fetchone()

        if item:
            # 将id转为整数
            item['id'] = int(item['id'])
            # 处理可能的NULL值
            item['another_name'] = item['another_name'] if item['another_name'] else ""
            return jsonify(item)
        else:
            return jsonify({"error": "Item not found"}), 404

    except pymysql.Error as e:
        return jsonify({"error": str(e)}), 500


# 登录接口
@app.route('/api/login', methods=['POST'])
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')

    if not username or not password:
        return jsonify({"error": "用户名和密码不能为空"}), 400

    try:
        conn = get_db_connection()
        if not conn:
            return jsonify({"error": "数据库连接失败"}), 500

        with conn.cursor() as cursor:
            cursor.execute("SELECT * FROM users WHERE username = %s AND password = %s", (username, password))
            user = cursor.fetchone()

        if user:
            # 登录成功，这里可以返回用户信息或token
            return jsonify({"message": "登录成功", "user": user}), 200
        else:
            return jsonify({"error": "用户名或密码错误"}), 401

    except pymysql.Error as e:
        print(f"登录查询数据库失败: {e}")
        return jsonify({"error": "登录失败，请稍后重试"}), 500


# 注册接口
@app.route('/api/register', methods=['POST'])
def register():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')

    if not username or not password:
        return jsonify({"error": "用户名和密码不能为空"}), 400

    try:
        conn = get_db_connection()
        if not conn:
            return jsonify({"error": "数据库连接失败"}), 500

        with conn.cursor() as cursor:
            # 检查用户名是否已存在
            cursor.execute("SELECT * FROM users WHERE username = %s", (username,))
            existing_user = cursor.fetchone()
            if existing_user:
                return jsonify({"error": "用户名已存在"}), 400

            # 插入新用户
            cursor.execute("INSERT INTO users (username, password) VALUES (%s, %s)", (username, password))
            conn.commit()

        return jsonify({"message": "注册成功"}), 200

    except pymysql.Error as e:
        print(f"注册查询数据库失败: {e}")
        return jsonify({"error": "注册失败，请稍后重试"}), 500
    finally:
        if conn:
            conn.close()


if __name__ == '__main__':
    print("启动水果蔬菜信息API服务...")
    print("API服务运行在: http://localhost:3000")
    app.run(host='0.0.0.0', port=3000, debug=True)